package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService catBrandRelation;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类及其子分类， 已数的类型展示。
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntitie ->{
            if(categoryEntitie.getParentCid()== 0){
                return true;
            }else{
                return false;
            }
        }
        ).map((menu) -> {
            //映射 递归 给每个父节点分类添加子节点菜单。
            menu.setChildren(getCategoryChildren(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            //添加排序
            return (menu1.getSort()==null ? 0: menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    //递归查出所有菜单的子菜单
    private List<CategoryEntity> getCategoryChildren(CategoryEntity menu, List<CategoryEntity> all) {
        List<CategoryEntity> list = all.stream().filter(category->
                category.getParentCid().equals(menu.getCatId())
        ).map((menuu) ->{
            menuu.setChildren(getCategoryChildren(menuu, all));
            return menuu;
        }).sorted((menu1, menu2) -> {
            //添加排序
            return (menu1.getSort()==null ? 0: menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        findParentPath(catelogId,list);

        Collections.reverse(list);

        return list.toArray(new Long[list.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if(StringUtils.isNotBlank(category.getName())){
            //修改分类同时修改对应的 品牌分类的内容
            catBrandRelation.updateCascadeCategory(category.getCatId(),category.getName());
        }
    }

    private List<Long> findParentPath(Long catelogId, List<Long> list) {
        list.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),list);
        }
        return list;
    }


    ////获取根分类
    @Cacheable(value = {"category"},key = "'level1Category'")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        LambdaQueryWrapper<CategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryEntity::getParentCid,0);
        List<CategoryEntity> list = this.list(queryWrapper);
        return list;
    }

    //获取分类json 数据
    @Override
    @Cacheable(value = {"category"},key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> entityList = this.list();

        //获取到根级分类， 一级菜单
        List<CategoryEntity> level1Category = getParentCid(entityList,0L);
        // 循环一级菜单  将    key：一级菜单ID | value：List<Catalog2Vo>
        Map<String, List<Catalog2Vo>> collect = level1Category.stream().collect(Collectors.toMap(item -> item.getCatId().toString(), l1 -> {
            //根据 一级菜单id 找到二级菜单
            List<CategoryEntity> level2 = getParentCid(entityList,l1.getCatId());

            //将CategoryEntity 转为 Catalog2Vo
            List<Catalog2Vo> collect2 = null;
            if (CollectionUtils.isNotEmpty(level2)) {
                collect2 = level2.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(l1.getCatId().toString(), l2.getCatId().toString(), l2.getName(), null);

                    //找出三级菜单
                    List<CategoryEntity> level3 = getParentCid(entityList,l2.getCatId());

                    if(CollectionUtils.isNotEmpty(level3)){
                        //将 level3-》CategoryEntity  转为 Catalog3Vo
                        List<Catalog2Vo.Catalog3Vo> collect3 = level3.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo =
                                    new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());

                        catalog2Vo.setCatalog3List(collect3);
                    }

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return collect2;
        }));

        return collect;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> entityList,Long pId) {
        List<CategoryEntity> collect = entityList.stream().filter(item -> {
            return item.getParentCid().equals(pId);
        }).collect(Collectors.toList());
        return collect;
    }

}